import { useModel } from "umi";
import { useReactive } from "ahooks";

const useObjects = () => {
    const { remoteData } = useModel("global");

    const state = useReactive({
        objectLoading: false,
        objects: [],
        selectedObject: null,
        appLoading: false,
        applications: [],
        selectedApplication: null,
        submitLoading: false,
    });

    const loadObjects = async () => {
        state.objectLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/developer/organization/application/getObjects",
            params: {
                order: [["aoName", "ASC"]],
            },
        });
        state.objects = res || [];
        state.selectedObject = state.objects.find((item) => item.aoName === state.selectedObject?.aoName);
        !state.selectedObject && state.objects.length > 0 && (state.selectedObject = state.objects[0]);
        state.objectLoading = false;
    };

    const setSelectedObject = (data) => (state.selectedObject = data);

    const loadObjectApplications = async () => {
        state.appLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/developer/organization/application/getObjectApplications",
            params: {
                aoName: state.selectedObject.aoName,
                order: [["appName", "ASC"]],
            },
        });
        state.applications = res || [];
        state.selectedApplication = state.applications.find((item) => item.appUuid === state.selectedApplication?.appUuid);
        !state.selectedApplication && state.applications.length > 0 && (state.selectedApplication = state.applications[0]);
        state.appLoading = false;
    };

    const setSelectedApplication = (data) => (state.selectedApplication = data);

    return { ...state, loadObjects, setSelectedObject, loadObjectApplications, setSelectedApplication };
};

export default useObjects;
